package com.codechuan.hallo_internal.floatwindow;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codechuan.hallo_internal.R;
import com.codechuan.hallo_internal.common.Constant;
import com.codechuan.hallo_internal.floatwindow.log.LogManager;
import com.codechuan.hallo_internal.floatwindow.log.LogTextureView;
import com.codechuan.hallo_internal.thread.MainThread;
import com.codechuan.hallo_internal.ui.login.LoginActivity;
import com.codechuan.hallo_internal.utils.ContextUtil;
import com.codechuan.hallo_internal.utils.DialogUtil;
import com.codechuan.hallo_internal.utils.HalloProjectHttpUtil;
import com.codechuan.hallo_internal.utils.MyProjectHttpUtil;

import java.util.concurrent.CopyOnWriteArrayList;


public class FloatWindowManager {
    private final String TAG = "FloatWindowManager";
    private final WindowManager windowManager;

    private static FloatWindowManager instance = new FloatWindowManager();
    private final LayoutInflater inflater;

    private View toolView;
    private View logView;
    private View handlerView;
    private WindowManager.LayoutParams layoutParams;
    private ObjectAnimator animator;

    private boolean isStartAnimator = false;
    public static ImageView tvFunction1;

    public static FloatWindowManager get() {
        return instance;
    }


    private FloatWindowManager() {
        inflater = LayoutInflater.from(ContextUtil.application);
        windowManager = (WindowManager) ContextUtil.application.getSystemService(Context.WINDOW_SERVICE);
    }


    private boolean isStart = false;

    public void showToolView() {
        if (toolView != null) {
            return;
        }
        toolView = inflater.inflate(R.layout.window_tool_view, null, false);
        toolView.findViewById(R.id.tvFunction).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hindAllView();
                showHandlerView();
            }
        });
        tvFunction1 = toolView.findViewById(R.id.tvFunction1);
        updateBtStartUI();
        tvFunction1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "点击了功能一");
                isStart = !isStart;
                updateBtStartUI();
            }
        });
        // 日志
        ImageView tvFunction2 = toolView.findViewById(R.id.tvFunction2);
        tvFunction2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "点击了功能二");
                if (logView == null) {
                    showLogView();
                } else {
                    hindLogView();
                }
            }
        });
      /*  toolView.findViewById(R.id.tvFunction3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "点击了功能三");
            }
        });*/
        toolView.findViewById(R.id.tvFunction4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "点击了功能四");
                // 校验是否登录
                if (!Constant.is_login) {
                    Constant.handler.post(() -> {
                        DialogUtil.showDialog(ContextUtil.context, "请先登录~");
                    });
                    return;
                }
                Intent intent = new Intent(ContextUtil.application, LoginActivity.class);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                ContextUtil.application.startActivity(intent);
            }
        });
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.gravity = Gravity.START | Gravity.CENTER_VERTICAL;
        windowManager.addView(toolView, layoutParams);
    }
    private void updateBtStartUI() {
        if (toolView != null) {
            if (isStart) {
                FloatWindowManager.get().startAnimator();
                tvFunction1.setImageResource(R.mipmap.icon_start_true);
                if (Constant.isStartTask) {
                    return;
                }
                Constant.isStartTask = true;
                if (Constant.cityInfo == null) {
                    Constant.handler.post(() -> DialogUtil.showDialog(ContextUtil.context, "请先定位,精准到省市区哦~"));
                    return;
                }
                // 订单列表初始化
                new Thread(() -> {
                    JSONObject jsonObject = HalloProjectHttpUtil.getWeChatMiniMyOrderOrMyScheduleOrder();
                    if (jsonObject != null && jsonObject.getString("code").equals("0")) {
                        // 获取行程数组
                        JSONArray data = jsonObject.getJSONArray("data");
                        for (Object datum : data) {
                            JSONObject dataList = JSONObject.parseObject(datum.toString());
                            JSONArray paxOrderList = dataList.getJSONArray("paxOrderList");
                            for (Object o : paxOrderList) {
                                JSONObject jsonObject1 = JSONObject.parseObject(o.toString());
                                String string = jsonObject1.getString("passengerJourneyGuid");
                                Constant.orderList.append(string).append(",");
                            }
                        }
                    }
                    LogManager.get().startLog();
                    if (jsonObject != null && jsonObject.getString("code").equals("103")) {
                        Constant.isStart = false;
                        Constant.handler.post(() -> {
                            DialogUtil.showDialog(ContextUtil.context, "主号token过期，请重新打开软件~");
                        });
                        Constant.executorService.execute(() -> {
                            // 修改用户token状态
                            MyProjectHttpUtil.updateAccountTokenStatus();
                        });
                        Constant.handler.post(() -> {
                            // 修改ui
                            tvFunction1.setImageResource(R.mipmap.icon_start_false);
                        });
                    }
                }).start();
                if (!Constant.isStart) {
                    Constant.isStart = true;
                    new Thread(new MainThread(Constant.cityInfo)).start();;
                    FloatWindowManager.get().startAnimator();
                    tvFunction1.setImageResource(R.mipmap.icon_start_true);
                }
            } else {
                tvFunction1.setImageResource(R.mipmap.icon_start_false);
                FloatWindowManager.get().stopAnimator();
                if (!Constant.isStartTask) {
                    return;
                }
                Constant.isStartTask = false;
                // 关闭刷新
                Constant.isStart = false;
                LogManager.get().stopLog();
            }
        }
    }
    public static void updateIcon() {
        tvFunction1.setImageResource(R.mipmap.icon_start_false);

    }



    public void showHandlerView() {
        if (handlerView != null) {
            return;
        }
        handlerView = inflater.inflate(R.layout.float_window_handler_view, null, false);
        handlerView.setOnTouchListener(new View.OnTouchListener() {
            private float lastX, lastY;

            private boolean isMove = false;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isMove = false;
                        int[] location = new int[2];
                        handlerView.getLocationOnScreen(location);
                        layoutParams.x = location[0];
                        layoutParams.y = location[1] - Constant.getStatusBarHeight();
                        lastX = event.getRawX();
                        lastY = event.getRawY();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        float rawX = event.getRawX();
                        float rawY = event.getRawY();
                        float distanceX = (rawX - lastX);
                        float distanceY = (rawY - lastY);
                        lastX = rawX;
                        lastY = rawY;
                        layoutParams.x += (int) distanceX;
                        layoutParams.y += (int) distanceY;
                        if (Math.abs(distanceY) > 10 || Math.abs(distanceX) > 10) {
                            isMove = true;
                        } else {
                            return true;
                        }
                        layoutParams.gravity = Gravity.TOP | Gravity.START;
                        windowManager.updateViewLayout(handlerView, layoutParams);
                        return true;
                    case MotionEvent.ACTION_UP:
                        if (!isMove) {
                            hindHandlerView();
                            showToolView();
                        }
                        return true;
                    default:
                        return false;
                }
            }
        });
        layoutParams = new WindowManager.LayoutParams();
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.gravity = Gravity.START | Gravity.CENTER_VERTICAL;
        windowManager.addView(handlerView, layoutParams);
        if (isStartAnimator) {
            startAnimator();
        }
    }


    public void showLogView() {
        if (logView != null) {
            return;
        }
        logView = inflater.inflate(R.layout.float_window_log_view, null, false);

        rvLog = logView.findViewById(R.id.rvLog);

        LogManager.get().initLog(rvLog);
        LogManager.get().startLog();

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        layoutParams.x = -30;
        layoutParams.gravity = Gravity.TOP;
        windowManager.addView(logView, layoutParams);
    }

    public void hindHandlerView() {
        if (handlerView != null) {
            windowManager.removeView(handlerView);
            handlerView = null;
        }
    }

    public void hindToolView() {
        if (toolView != null) {
            windowManager.removeView(toolView);
            toolView = null;
        }
    }

    public void hindLogView() {
        if (logView != null) {
            windowManager.removeView(logView);
            logView = null;
        }
    }

    public void hindAllView() {
        if (toolView != null) {
            windowManager.removeView(toolView);
            toolView = null;
        }
    }


    private LogTextureView rvLog;


    public void startAnimator() {
        if (handlerView != null) {
            isStartAnimator = true;
            animator = ObjectAnimator.ofFloat(handlerView, "rotation", 0, 360);
            animator.setDuration(300);
            animator.setRepeatCount(-1);
            animator.start();
        } else {
            isStartAnimator = true;
        }
    }


    public void stopAnimator() {
        if (handlerView != null) {
            isStartAnimator = false;
            handlerView.clearAnimation();
        } else {
            isStartAnimator = false;
        }
    }


}
